// http://127.0.0.1:9981/hulu-obj-data/color-glb/base_basic_shaded.glb

import BackBtn from '@components/globalComponents/BackBtn';
import React, { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

function XBotGLB(): React.ReactElement {
  // 模型容器引用，用于挂载Three.js场景
  const mountRef = useRef<HTMLDivElement>(null);
  // 动画混合器，用于播放模型动画
  const mixerRef = useRef<THREE.AnimationMixer | null>(null);
  // 时钟，用于更新动画
  const clockRef = useRef<THREE.Clock>(new THREE.Clock());
  // 模型引用，用于存储加载的模型
  const modelRef = useRef<THREE.Group | null>(null);
  // 当前播放的动画动作
  const actionRef = useRef<THREE.AnimationAction | null>(null);
  // 动画状态
  const [isPlaying, setIsPlaying] = useState<boolean>(true);

  let model: any; // 模型引用，用于存储加载的模型
  let skeleton: any; // 骨骼引用，用于存储模型骨架
  let mixer: any;
  let numAnimations: number = 0;
  const allActions = [];

  // 动画状态
  const baseActions: any = {
    idle: { weight: 1 },
    walk: { weight: 0 },
    run: { weight: 0 },
  };
  const additiveActions: any = {
    sneak_pose: { weight: 0 },
    sad_pose: { weight: 0 },
    agree: { weight: 0 },
    headShake: { weight: 0 },
  };
  function activateAction(action: any) {
    const clip = action.getClip();
    const settings = baseActions[clip.name] || additiveActions[clip.name];
    setWeight(action, settings.weight);
    action.play();
  }
  function setWeight(action, weight) {
    action.enabled = true;
    action.setEffectiveTimeScale(1);
    action.setEffectiveWeight(weight);
  }
  useEffect(() => {
    if (!mountRef.current) return;

    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xeeeeee);

    const camera = new THREE.PerspectiveCamera(
      75,
      mountRef.current.clientWidth / mountRef.current.clientHeight,
      0.1,
      100,
    );

    // 将相机位置调整，使视角向下，更好地观察偏下的模型
    camera.position.set(1, 1.5, 4);

    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(
      mountRef.current.clientWidth,
      mountRef.current.clientHeight,
    );
    mountRef.current.appendChild(renderer.domElement);

    const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
    scene.add(ambientLight);

    // 添加方向光，使模型有阴影效果
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
    directionalLight.position.set(5, 5, 10);
    scene.add(directionalLight);

    const loader = new GLTFLoader();
    loader.load(
      'http://127.0.0.1:9981/robot/xbot.glb',
      (gltf) => {
        // 将模型整体下移，使其居中偏下显示
        gltf.scene.position.y = -1;
        // 增加模型缩放比例，使其在画面中显示得更大
        gltf.scene.scale.set(1.5, 1.5, 1.5);
        model = gltf.scene; // 获取模型
        scene.add(model);

        skeleton = new THREE.SkeletonHelper(model);
        skeleton.visible = true; // 显示骨骼辅助线
        scene.add(skeleton); // 添加骨骼辅助线

        const { animations } = gltf;
        mixer = new THREE.AnimationMixer(model);
        numAnimations = animations.length;

        console.log('mixer:', mixer);
        console.log('numAnimations:', numAnimations);

        model.traverse((object: any) => {
          if (object.isMesh) {
            object.castShadow = true;
          }
        });
        modelRef.current = gltf.scene;

        // 检查模型是否包含动画----？ 需要模型中包含动画
        if (gltf.animations && gltf.animations.length > 0) {
          // 创建动画混合器
          mixerRef.current = new THREE.AnimationMixer(gltf.scene);

          // 如果没有特定动画，播放第一个动画[0, 1, ..., numAnimations - 1]
          actionRef.current = mixerRef.current.clipAction(gltf.animations[3]);
          actionRef.current.play();
          console.log('播放默认动画');
        } else {
          console.log('模型没有内置动画，将添加说话和手势的动画效果');
        }
      },
      undefined,
      (error) => {
        console.error('加载 GLB 模型失败:', error);
      },
    );

    const controls =
      new (require('three/examples/jsm/controls/OrbitControls').OrbitControls)(
        camera,
        renderer.domElement,
      );
    controls.enableDamping = true;

    // 动画循环函数
    const animate = () => {
      requestAnimationFrame(animate);

      // 更新动画混合器
      if (mixerRef.current && isPlaying) {
        const delta = clockRef.current.getDelta();
        mixerRef.current.update(delta);
      } else if (modelRef.current) {
        // 如果没有内置动画，添加说话和手势的模拟效果
        if (isPlaying) {
          // 模拟说话效果 - 轻微上下移动头部
          const head = modelRef.current.getObjectByName('head');
          if (head) {
            head.position.y = -1 + 0.01 * Math.sin(Date.now() * 0.005);
          }

          // 模拟手势效果 - 手臂摆动
          const rightArm = modelRef.current.getObjectByName('rightArm');
          const leftArm = modelRef.current.getObjectByName('leftArm');

          if (rightArm) {
            rightArm.rotation.z = 0.2 * Math.sin(Date.now() * 0.003);
          }
          if (leftArm) {
            leftArm.rotation.z =
              -0.2 * Math.sin(Date.now() * 0.003 + Math.PI / 2);
          }
        }
      }

      controls.update();
      renderer.render(scene, camera);
    };
    animate();

    const handleResize = () => {
      if (!mountRef.current) return;
      camera.aspect =
        mountRef.current.clientWidth / mountRef.current.clientHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(
        mountRef.current.clientWidth,
        mountRef.current.clientHeight,
      );
    };
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      if (mountRef.current && renderer.domElement) {
        mountRef.current.removeChild(renderer.domElement);
      }
      // 清理动画相关资源
      if (mixerRef.current) {
        mixerRef.current.stopAllAction();
      }
      renderer.dispose();
    };
  }, [isPlaying]);

  function createPanel() {
    // 创建 GUI 面板
    const panel = new GUI({ width: 310 });
    const folider1 = panel.addFolder('base Actions');
  }
  // 动画控制函数
  const playAnimation = () => {
    if (actionRef.current) {
      actionRef.current.play();
    }
    setIsPlaying(true);
  };

  const pauseAnimation = () => {
    if (actionRef.current) {
      actionRef.current.paused = true;
    }
    setIsPlaying(false);
  };

  const stopAnimation = () => {
    if (actionRef.current) {
      actionRef.current.stop();
    }
    setIsPlaying(false);
  };

  return (
    <div>
      {/* 返回首页按钮 */}
      <div
        style={{ position: 'absolute', top: '16px', left: '16px', zIndex: 10 }}
      >
        <BackBtn />
      </div>
      {/* 动画控制按钮 */}
      <div
        style={{
          position: 'absolute',
          bottom: '30px',
          left: '50%',
          transform: 'translateX(-50%)',
          zIndex: 10,
          display: 'flex',
          gap: '15px',
          backgroundColor: 'rgba(0,0,0,0.7)',
          padding: '10px 20px',
          borderRadius: '25px',
        }}
      >
        <button
          type="button"
          onClick={stopAnimation}
          style={{
            padding: '8px 16px',
            backgroundColor: '#ff4444',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
          }}
        >
          停止
        </button>
        <button
          type="button"
          onClick={pauseAnimation}
          style={{
            padding: '8px 16px',
            backgroundColor: '#ffaa00',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
          }}
        >
          暂停
        </button>
        <button
          type="button"
          onClick={playAnimation}
          style={{
            padding: '8px 16px',
            backgroundColor: '#00aa44',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
          }}
        >
          播放
        </button>
      </div>
      <div ref={mountRef} style={{ width: '100%', height: '100vh' }} />
    </div>
  );
}

export default XBotGLB;
